#pragma once
#include <memory>
#include <iostream>

#include"InetAddr.hpp"
#include "Socket.hpp"
#include "Connection.hpp"

class Listener
{
public:
    Listener(uint16_t port)
        : _port(port),
          _listensock(std::make_unique<tcp_Socket>())
    {
        _listensock->BuildListenSocket(port);
    }
    int Sockfd()
    {
        return _listensock->Sockfd();
    }
    void Accepter(Connection *conn)
    {
        // 需要循环进行，把所有的连接获取完
        while (true)
        {
            errno = 0;
            InetAddr addr;
            int code = 0;
            int sockfd = _listensock->Accepter(&addr,&code);
            if (sockfd > 0)
            {
                // 获取到连接
                LOG(INFO, "获取连接成功, 客户端: %s:%d, sockfd: %d\n", addr.IP().c_str(), addr.Port(), sockfd);
                conn->_R->AddConnection(sockfd, EPOLLIN, NormalConnection,addr);
            }
            else
            {
                // 判断是否读取完所有
                if (code == EWOULDBLOCK)
                {
                    LOG(INFO, "底层连接获取完毕\n");
                }
                else if (code == EINTR)
                    continue;
                else
                {
                    LOG(ERROR,"获取连接失败\n");
                    break;
                }
            }
        }
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
};